package com.glorysoft.tonglingxjpda.ui.function.view

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.View
import androidx.annotation.Nullable
import com.bumptech.glide.Glide
import com.glorysoft.tonglingxjpda.BR
import com.glorysoft.tonglingxjpda.R
import com.glorysoft.tonglingxjpda.base.BaseActivity
import com.glorysoft.tonglingxjpda.customview.SelectorPicDialog
import com.glorysoft.tonglingxjpda.databinding.ActivityKyhInfoBinding
import com.glorysoft.tonglingxjpda.entity.BomEntity
import com.glorysoft.tonglingxjpda.entity.ui.ToastMessageBean
import com.glorysoft.tonglingxjpda.ui.function.viewmodel.KYHInfoViewModel
import com.glorysoft.tonglingxjpda.utils.BitmapUtils
import com.pda.platform.ui.ui_pdaplatform.activity_public.FreeUI_CameraActivity
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PictureUtils
import com.zhihu.matisse.Matisse
import kotlinx.android.synthetic.main.activity_kyh_info.*
import kotlinx.android.synthetic.main.activity_title.*
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

/**
 * FileName: KYHInfoActivity
 * Author: XJH
 * Date: 2021/7/16 17:53
 * Description:
 * History:
 */
class KYHInfoActivity : BaseActivity<KYHInfoViewModel,ActivityKyhInfoBinding>(),
    SelectorPicDialog.CameraAndAlbumListener {

    private var docID = ""
    private var iconPath = ""
    private var entity : BomEntity? = null
    override fun layoutId(): Int {
        return R.layout.activity_kyh_info
    }

    override fun initVariableId(): Int {
        return BR.kyhInfoViewmodel
    }

    override fun initView(savedInstanceState: Bundle?) {
        setTitle("刻字号")
        val extras = intent.extras
        docID = extras!!.getString("POID","")

        entity = intent.getSerializableExtra("DATA") as BomEntity
        setRightListener("保存") {
            showLoading()
            viewModel.saveKyh(docID,tvPartName.text.toString(),iconPath,"COMPONENTUMITSAVE")
        }
        tvPartName.text = entity?.PARTNAME
        tvPartDesc.text = entity?.WORKORDERTYPE
        tvReserved8.text = entity?.RESERVED8
        iconPath = entity?.localPath.toString()
        if (iconPath.isNotEmpty()){
            Glide.with(this).load(iconPath)
                .error(R.drawable.ic_launcher_background).into(ivIcon)
        }
        viewModel.initPart(docID, entity!!)
        rvkyh.setEmptyView(kyhEmpty)
        rvkyh.adapter = viewModel.partAdapter
        viewModel.partAdapter?.setOnItemClickListener { _, _, position ->
            val bundle = Bundle()
            bundle.putSerializable("DATA",viewModel.partAdapter!!.data[position])
            bundle.putString("DOCID",docID)
            startActivity(DefectActivity::class.java,bundle)
        }
        tvRight2.visibility = View.VISIBLE
        tvRight2.text = "修改"
        tvRight2.setOnClickListener{
            showLoading()
            viewModel.saveKyh(docID,tvPartName.text.toString(),iconPath,"COMPONENTUMITUPDATE")
        }
    }

    override fun initData() {
        viewModel.defUI.startActivity.observe(this){
            setResult(RESULT_OK)
            finish()
        }

        viewModel.defUI.callObserve.observe(this){
            when(it.type){
                0 ->{
                    when(it.item){
                        "FAIL" ->{
                            dismissLoading()
                        }
                    }
                }
            }
        }

        val mDialog = SelectorPicDialog()
        mDialog.setTitle("请选择照片")
        mDialog.setOnCameraAndAlbumListener(this)
        mDialog.setSelectVideo(true) //相册可以选择照片

        mDialog.setRecordVideo(false) //可以录制视频

        ivIcon.setOnClickListener{
            mDialog.show(supportFragmentManager, "ICON_DIALOG")
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, @Nullable data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //取消选择，将上次的文件置为空，重新选择更换的文件
        if (resultCode == RESULT_CANCELED) {
            return
        }
        if (resultCode == RESULT_OK || resultCode == 101){
            when (requestCode) {
                SelectorPicDialog.REQUEST_CODE_LOCAL -> if (data != null) {
                    val pathList = Matisse.obtainPathResult(data)
                    isIconOrVideo(pathList[0], SelectorPicDialog.REQUEST_CODE_LOCAL)
                }
                SelectorPicDialog.REQUEST_CAMEAR -> {
                    val path = BitmapUtils.getPath(this, BitmapUtils.imageUri)
                    isIconOrVideo(path, SelectorPicDialog.REQUEST_VIDEO)
                }
                101 ->{
                    val path = data!!.getStringExtra("path")
                    isIconOrVideo(path, SelectorPicDialog.REQUEST_VIDEO)
                }
            }
        }

    }

    private fun isIconOrVideo(path: String, requestVideo: Int) {
        if (path.contains(".mp4")) {  //先判断地址是视频还是图片
            viewModel.defUI.toastEvent.value = ToastMessageBean("不能选择视频，请重新选择！",false)
        } else {
            //照片
//                val bitmap = BitmapFactory.decodeFile(path)
//            val compressImage = FreeApi_PictureUtils.compressImage(bitmap, 30)
//            saveFile(compressImage,"compress.jpg")
            ivIcon.setImageURI(Uri.fromFile(File(path)))
            iconPath = path
        }
    }

    @Throws(IOException::class)
    private fun saveFile(bm: Bitmap, fileName: String) {
        val SAVE_PIC_PATH = if (Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED, ignoreCase = true)
        ) Environment.getExternalStorageDirectory().absolutePath else "/mnt/sdcard" //保存路径
        val subForder = "$SAVE_PIC_PATH/Andun/"
        val foder = File(subForder)
        if (!foder.exists()) foder.mkdirs()
        val myCaptureFile = File(subForder, fileName)
        Log.e("TAG", "协议图片保持。。。。。。。。$myCaptureFile")
        if (!myCaptureFile.exists()) myCaptureFile.createNewFile()
        val bos = BufferedOutputStream(FileOutputStream(myCaptureFile))
        val isSuccess = bm.compress(Bitmap.CompressFormat.JPEG, 100, bos)
        bos.flush()
        bos.close()
        if (isSuccess) {
            //保存图片后发送广播通知更新相册数据库
            val uri = Uri.fromFile(myCaptureFile)
            this.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri))
        }
    }
    override fun OnSuccess(type: String?) {
        when (type) {
            SelectorPicDialog.TYPE_VIDEO -> FreeUI_CameraActivity.goCameraActivity(
                this,
                SelectorPicDialog.fileFolderPath
            )
            SelectorPicDialog.TYPE_ALBUM -> if (SelectorPicDialog.mSelectVideo) {
                BitmapUtils.selectPicAndTakePic(this, SelectorPicDialog.REQUEST_CODE_LOCAL, 1)
            } else {
                BitmapUtils.selectPicFromLocal(this, SelectorPicDialog.REQUEST_CODE_LOCAL, 1)
            }
            SelectorPicDialog.TYPE_CAMERA ->
            BitmapUtils.takePicture(this,SelectorPicDialog.REQUEST_CAMEAR)
//            FreeUI_CameraActivity.goCameraActivity(
//                this,
//                SelectorPicDialog.fileFolderPath
//            )
        }
    }

    override fun OnFailed(type: String?) {
        viewModel.defUI.toastEvent.value = ToastMessageBean("当前权限开启失败，请重试！",false)
    }

    override fun OnFailedNotAsking(type: String?) {
        viewModel.defUI.toastEvent.value = ToastMessageBean("当前权限开启失败，并且设置为不在询问，请去设置界面重新开启！",false)
    }
}